<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\api\controller\BaseController;

class MemberController extends BaseController
{

	/**
	*用户信息
	*
	**/
	public function index()
	{
		$member_id = $this->member_id;

		$memModel = new \app\home\model\MemberModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname, mobile, logo, grade, money, status');
		//$meminfo['logo'] = json_img_add_url('/upload/'. $meminfo['logo']);

		return return_msg(200, '', $meminfo);
	}


	/**
	*
	*首次登陆 - 设置用户昵称、性别、生日
	**/
	public function oneLoginSetInfo()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$data = $this->request->param();

		//判断是否位设置过昵称、性别、生日
		$info = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, baby_name, baby_birthday, baby_sex');
		//都设置过，就提醒不能再设置
		if(!empty($info['baby_name']) && !empty($info['baby_birthday']) && !empty($info['baby_sex']))
		{
			return return_msg(20020, '该账户已设置宝宝资料');
		}

		//校验参数
		$validate = new \app\api\validate\MemberValidate();
		if(!$validate->scene('set_info')->check($data))
        {
            return return_msg(20021, $validate->getError());
        }

        //开始设置
        $add_data = [
        	'baby_name' => $data['baby_name'],
        	'baby_birthday' => $data['baby_birthday'],
        	'baby_sex' => $data['baby_sex'],
        ];

        $res = $memModel->updateMemberInfo($member_id, $add_data);
		if(empty($res))
		{
			return return_msg(20022, '设置宝宝资料失败，系统错误');
		}else{
			return return_msg(200, '');
		}
	}



	/**
	*
	*设置个人资料页面
	**/
	public function set()
	{
		$member_id = $this->member_id;

		$memModel = new \app\home\model\MemberModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname, logo, mobile, grade, money, status');
		$meminfo['logo'] = json_img_add_url('/upload/'. $meminfo['logo']);

		return return_msg(200, '', $meminfo);

	}


	/**
	*
	*设置-昵称
	**/
	public function setName()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname');

		return return_msg(200, '', $meminfo);
	}


	/**
	*
	*保存昵称-操作
	**/
	public function saveName()
	{
		$member_id = $this->member_id;

		$nickname = $this->request->param('nickname', '');
		if(empty($nickname)){
			 return return_msg(2001, '请输入昵称');
		}

		$memModel = new \app\home\model\MemberModel();

		//该昵称是否已被使用
		/*$where = [
			['member_id', 'neq', $member_id],
			['nickname', 'eq', $nickname]

		];
		$info = $memModel->geetMemberWhereReturnInfo($where, 'member_id');
		
		if(!empty($info))
		{
			return return_msg(2003, '该昵称已被别人使用');
		}*/


		//开始修改
		
		$res = $memModel->updateMemberInfo($member_id, ['nickname' => $nickname]);
		if($res === false)
		{
			return return_msg(2002, '更新昵称失败，系统错误');
		}else{
			return return_msg(200, '');
		}
	}


	/**
	*
	*设置-手机号
	**/
	public function setPhone()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, mobile');

		return return_msg(200, '', $meminfo);
	}


	/**
	*
	*保存手机号-操作
	**/
	public function savePhone()
	{
		$member_id = $this->member_id;

		$mobile = $this->request->param('mobile', '');

		if(empty($mobile) || !cmf_check_mobile($mobile)){
			return return_msg(2001, '请输入正确的手机号');
		}

		$memModel = new \app\home\model\MemberModel();

		//该昵称是否已被使用
		$where = [
			['member_id', 'neq', $member_id],
			['mobile', 'eq', $mobile]

		];
		$info = $memModel->geetMemberWhereReturnInfo($where, 'member_id');
		if(!empty($info))
		{
			return return_msg(2003, '该手机号已被别人使用');
		}


		//开始修改
		$res = $memModel->updateMemberInfo($member_id, ['mobile' => $mobile]);
		if($res === false)
		{
			return return_msg(2002, '更新手机号失败，系统错误');
		}else{
			return return_msg(200, '');
		}
	}




	/**
	*
	*
	*用户 - 我的团队
	**/
	public function myTeam()
	{
		$type = $this->request->param('type', 1, 'intval');//1=直属 2=扩散 3=访客
		$page = $this->request->param('page', 1, 'intval');//页码

		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$awardModel = new \app\home\model\OrderAwardModel();
		$accessModel = new \app\home\model\MemberAccessModel();
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, grade, parent, invite, status');
		
		//我的一，二级总人数
		$meminfo['team_count'] = $memModel->getMyInviteCounts($meminfo['invite']);
	
		//上级-累计收益
		$where = [
			['invite', '=', $meminfo['parent']],
		];
		$parent_meminfo = $memModel->geetMemberWhereReturnInfo($where, 'member_id, nickname, logo, grade, parent, invite, status');
		if(!empty($parent_meminfo))
		{
			$parent_meminfo['award_count'] = $awardModel->memberOrderCountsEarnings($parent_meminfo['member_id']);
		}else{
			$parent_meminfo = null;
		}
		

		//直属下级-已购课列表
		if($type == 1)
		{
			//$list = $memModel->getMemberSubordinate($meminfo['invite'], $page);

			$list = $memModel->getMemberZhishuXiaji($meminfo['invite'], $page);
		}elseif($type == 2){
			//二级下级-已购课列表
			//$list = $memModel->getMemberTwoSubordinate($meminfo['invite'], $page);
			$list = $memModel->getMemberZhishuXiaXiaji($meminfo['invite'], $page);
		}else{
			//我的访客列表
			$access_list = $accessModel->accessList($meminfo['member_id'], $page);
			$access_list = !empty($access_list) ? $access_list : [];
			$list = [];
			foreach($access_list as $k => $val)
			{
				$access_info = $memModel->getMemberIdWhereMemberId($val['access_id'], 'member_id, nickname, parent, logo, grade, add_time');
				//未绑定邀请人的访客，才展示
				if(!empty($access_info) && $access_info['parent'] == '')
				{
					$list[] = $access_info;
				}
			}

		}
		
		//总人数
		$count_list = $memModel->getMyTeamMiddleCount($meminfo['member_id'], $meminfo['invite']);

		return return_msg(200, '', ['page' => $page,'type' =>$type, 'team_count' => $meminfo['team_count'], 'parent_meminfo' => $parent_meminfo, 'list' => $list, 'count_list' => $count_list]);	
	}




	/**
	*
	*
	*查询-邀请码查询联系人
	**/
	public function getMySubordinate()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$accessModel = new \app\home\model\MemberAccessModel();
		$invite_code = $this->request->param('invite_code', '');//海报自带的邀请码
		if(empty($invite_code)) return return_msg(2001, '请输入要查询的邀请码');

		//先判断自己是否有上级
		$info = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, parent');

		//存在邀请码+未绑定上级，进行判断处理
		if(empty($info['parent']))
		{
			//查找邀请人信息
			$where = [
				['invite', '=', $invite_code]
			];
			$pinfo = $memModel->geetMemberWhereReturnInfo($where, 'member_id, nickname, logo, grade');
			//存在邀请人，并且为顾问
			if(empty($pinfo) || ($pinfo['grade'] == 1))
			{
				return return_msg(2003, '未找到邀请人，请输入正确的顾问邀请码');
			}else{
				return return_msg(200, '', $pinfo);
			}
		}else{
			return return_msg(2002, '您已有邀请人');
		}
	}



	/**
	*
	*手动-绑定邀请关系
	*
	**/
	public function manualBindingInvite()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$accessModel = new \app\home\model\MemberAccessModel();
		$invite_code = $this->request->param('invite_code', '');//海报自带的邀请码
		if(empty($invite_code)) return return_msg(2001, '请输入要查询的邀请码');

		//先判断自己是否有上级
		$info = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, parent');

		//存在邀请码+未绑定上级，进行判断处理
		if(empty($info['parent']))
		{
			//查找邀请人信息
			$where = [
				['invite', '=', $invite_code]
			];
			$pinfo = $memModel->geetMemberWhereReturnInfo($where, 'member_id, nickname, logo, grade');
			//存在邀请人，并且为用户
			if(empty($pinfo) || ($pinfo['grade'] == 1))
			{
				return return_msg(2003, '未找到邀请人，请输入正确的顾问邀请码');
			}else{
				//是否绑定了自己
				if(($member_id == $pinfo['member_id'])) return return_msg(2004, '不能绑定自己为邀请人');
				//是否 绑定了下级
				//$res = $this->getMemberIfInviteTop($pinfo['member_id']);
				//if(!empty($res)) return return_msg(2005, '不能绑定下级为邀请人');
				
				//开始绑定
				$time = date('Y-m-d H:i:s');
				$res = $memModel->updateMemberInfo($member_id, ['parent' => $invite_code, 'bind_time' => $time]);
                if(empty($res))
                {
                	return return_msg(2006, '绑定失败，请稍后再试');
                }

                return return_msg(200, '绑定成功');
			}
		}else{
			return return_msg(2002, '您已有邀请人，请确认后再操作');
		}
	}



	/**
	*
	*查看-好友资料
	*
	**/
	public function lookMyFriend()
	{
		$member_id = $this->request->param('user_id', '');//好友ID
		if(empty($member_id)) return return_msg(2001, '好友ID不能为空');

		//开始查找
		 $memModel = new \app\home\model\MemberModel();
		 $awardModel = new \app\home\model\OrderAwardModel();
		 $where = [
		 	['member_id', '=', $member_id]
		 ];
		 $info = $memModel->geetMemberWhereReturnInfo($where, 'member_id, nickname, logo, wx_number, grade, invite,add_time');
		 if(empty($info)) return return_msg(2002, '不存在的用户信息，请确认后操作');

		 //查看-本月预估收益
		 $month = $awardModel->getMemberOrderPredictEarnings($member_id);
		 //累计预估收益
		 $month_all = $awardModel->getMemberOrderPredictEarnings($member_id, 1);

		 //本月邀请人数 
		 $month_invite = $memModel->monthInviteCounts($info['invite']);
		 //总邀请人数
		 $invite_all = $memModel->getMyInviteCounts($info['invite']);



		 $data = ['info' => $info, 'month' => $month, 'month_all' => $month_all , 'month_invite' => $month_invite, 'invite_all' => $invite_all];
		 return return_msg(200, '', $data);
	}




	/**
	*
	*设置-微信
	**/
	public function setWechat()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, wx_number');

		return return_msg(200, '', $meminfo);
	}



	
	/**
	*
	*保存微信号-操作
	**/
	public function saveWechat()
	{
		$member_id = $this->member_id;

		$wx_number = $this->request->param('wx_number', '');
		if(empty($wx_number)){
			return return_msg(2001, '请输入新的微信号');
		}

		$memModel = new \app\home\model\MemberModel();

		//开始修改
		$res = $memModel->updateMemberInfo($member_id, ['wx_number' => $wx_number]);
		if($res === false)
		{
			return return_msg(2001, '更新微信号失败，系统错误');
		}else{
			return return_msg(200, '');
		}
	}




	/**
	*
	*推广-收益
	*
	**/
	public function Promotion()
	{
		$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$awardModel = new \app\home\model\OrderAwardModel();
		$accessModel = new \app\home\model\MemberAccessModel();
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, logo, nickname, grade, money, invite, status');

		//累计收益
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['status', 'in', [1, 2]],
		];
		$count_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['count_money'] = $count_money;

		//即将到账
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['status', '=', 1],

		];
		$jj_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['jj_money'] = $jj_money;

		//今，昨，本月，上月 推广订单（数量）， 收益
		$jt_start_time = date('Y-m-d');
		$jt_end_time = date('Y-m-d 23:59:59');
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['add_time', '>=', $jt_start_time],
			['add_time', '<=', $jt_end_time],
			['status', 'in', [1,2]]
		];
		$today_count = $awardModel->getMermberCountsWhere($where);
		$today_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['today_count'] = $today_count;
		$meminfo['today_money'] = $today_money;


		//昨天
		$zt_start_time = date('Y-m-d', strtotime('-1 day'));
		$zt_end_time = date('Y-m-d');
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['add_time', '>=', $zt_start_time],
			['add_time', '<=', $zt_end_time],
			['status', 'in', [1,2]]
		];
		$zt_count = $awardModel->getMermberCountsWhere($where);
		$zt_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['zt_count'] = $zt_count;
		$meminfo['zt_money'] = $zt_money;


		//本月
		$by_start_time = date('Y-m-01 00:00:00');
		$by_end_time = date('Y-m-t 23:59:59');
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['add_time', '>=', $by_start_time],
			['add_time', '<=', $by_end_time],
			['status', 'in', [1,2]]
		];
		$by_count = $awardModel->getMermberCountsWhere($where);
		$by_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['by_count'] = $by_count;
		$meminfo['by_money'] = $by_money;



		//上个月
		$sy_start_time = date('Y-m-1 00:00:00', strtotime("last day of -1 month"));
		$sy_end_time = date('Y-m-01 00:00:00');
		
		$where = [
			['member_id', '=', $meminfo['member_id']],
			['add_time', '>=', $sy_start_time],
			['add_time', '<=', $sy_end_time],
			['status', 'in', [1,2]]
		];
		$sy_count = $awardModel->getMermberCountsWhere($where);
		$sy_money = $awardModel->getMermberCountsWhere($where, 'money');
		$meminfo['sy_count'] = $sy_count;
		$meminfo['sy_money'] = $sy_money;
		return return_msg(200, '', $meminfo);
	}



	/**
    *
    *用户-我的钱包
    *
    **/
    public function myWallet()
    {
    	$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$awardModel = new \app\home\model\OrderAwardModel();
		//查找用户信息
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname, logo, grade, money, status');

		//即将到账金额
		$count_money = $awardModel->getMemberOrderPredictEarnings($member_id, 1);

		$this->assign('meminfo', $meminfo);
		$this->assign('count_money', $count_money);
        return return_msg(200, '', ['meminfo' => $meminfo, 'count_money' => $count_money]);
    }



    /**
    *
    *申请提现操作
    *
    **/
    public function memberTx()
    {
    	$member_id = $this->member_id;
		$memModel = new \app\home\model\MemberModel();
		$awardModel = new \app\home\model\OrderAwardModel();
		$wdModel = new \app\home\model\WithdrawalsModel();
		$financeModel = new \app\home\model\FinanceModel();
		//查找用户信息
		$withdrawal_money = $this->request->param('withdrawal_money', '');//提现金额
		if(empty($withdrawal_money))
		{
			//$this->error('参数错误，非法请求');
			return return_msg(2001, '参数错误，非法请求');
		}

		//判断是否有小数
		$withdrawal_money = intval($withdrawal_money);
		if(!is_int($withdrawal_money))
		{
			//$this->error('提现金额必须是整数');
			return return_msg(2002, '提现金额必须是整数');
		}

		//不能小于5元 OR  不能大于5000元
		if(intval($withdrawal_money) < 5)
		{
			//$this->error('提现金额不能低于5元，非法请求');
			return return_msg(2003, '提现金额不能低于5元');
		}

		if(intval($withdrawal_money) > 1000)
		{
			//$this->error('提现金额不能低于5元，非法请求');
			return return_msg(2003, '单次提现金额不能超过1000元');
		}

		//余额是否够本次提现
		$meminfo = $memModel->getMemberIdWhereMemberId($member_id, 'member_id, nickname, logo, grade, money, status');
		if($withdrawal_money > $meminfo['money'])
		{
			//$this->error('余额不足，提现失败');
			return return_msg(2004, '余额不足，提现失败');
		}

		//当天提现累计金额不能大于5000元
		$tx_money = $wdModel->addMemberTx($member_id);
		if($tx_money >= 5000)
		{
			//$this->error('今天提现金额已达5000元，今日上限');
			return return_msg(2005, '今天提现金额已达5000元，今日上限');
		}

		$tx_number = $wdModel->addMemberTx($member_id, true);
		if($tx_number >= 5)
		{
			//$this->error('今天提现次数已达5次，今日上限');
			return return_msg(2006, '今天提现次数已达5次，今日上限');
		}

		Db::startTrans();
		//直接减去用户余额
		$alter_money = $meminfo['money'] - $withdrawal_money;
		$update = [
			'money' => $alter_money
		];
		$res = $memModel->updateMemberInfo($member_id, $update);
		if(empty($res))
		{
			Db::rollback();
			//$this->error('提现失败，系统错误');
			return return_msg(2007, '提现失败，系统错误');
		}


		//添加提现数据
		$add = [
			'member_id' => $member_id,
			'money' => $withdrawal_money,
		];
		$wd_id = $wdModel->addMemberTxInfo($add);
		if(empty($wd_id))
		{
			Db::rollback();
			//$this->error('系统繁忙，请稍后重试');
			return return_msg(2007, '系统繁忙，请稍后重试');
		}

		//增加财务日志
		$finance = [
			'member_id' => $member_id,
			'type' => 5,
			'money' => $withdrawal_money,
			'money_way' => 2,
			'remark' => '用户提现',
			'status' => 1,
			'before_money' => $meminfo['money'],
			'later_money' => ($meminfo['money'] - $withdrawal_money),
			'table_id' => $wd_id,
		];
		$res = $financeModel->addFinance($finance);
		if(empty($res))
		{
			Db::rollback();
			//$this->error('系统繁忙，请稍后重试');
			return return_msg(2008, '财务日志增加失败，系统错误');
		}

		Db::commit();

		//申请提现，通知消息
		$notice_contro = new NoticeController();
		$send_data = [
            'first' => ['value'=>'您的提现申请已提交', 'color'=>"#173177"],
            'keyword1' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
            'keyword2' => ['value'=> $withdrawal_money, 'color'=>'#173177'],
            'remark' => ['value'=>'预计3个工作日到账', 'color'=>'#173177'],
        ];
        $return_url = WEB_URL."/tx_list";
        $notice_contro->sendNoticeMessage('tx', $send_data, $return_url, '', $member_id);

		return return_msg(200, '提现成功', ['id' => $wd_id]);
    }
	
}